package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.Result;
import com.bwie.vo.PageUserVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-05-21 13:44:08
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Override
    public List getMenuTreeByUserId(Integer userId) {
        //--1 获取菜单列表
        List<TbMenu> list = tbUserMapper.getMenuTreeByUserId(userId);

        //--2 递归获取菜单树
        List<Tree<String>> menuTree = TreeUtil.build(list, "0", (menu, tree) -> {
            tree.setId("" + menu.getMenuId());
            tree.setName(menu.getMenuName());
            tree.setParentId("" + menu.getMenuPid());
            tree.putExtra("path", menu.getMenuPath());
        });

        return menuTree;
    }

    @Override
    public Result getUserList(PageUserVo pageUserVo) {
        //--1 构造分页参数
        Page<TbUser> page = new Page<>(pageUserVo.getPageNum(), pageUserVo.getPageSize());

        //--2 获取商户列表（分页查询）
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(pageUserVo.getKeyWord())) {
            wrapper.lambda().or().like(TbUser::getUserName, pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getNickName, pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getUserMobile, pageUserVo.getKeyWord());
            wrapper.lambda().or().like(TbUser::getUserEmail, pageUserVo.getKeyWord());
        }

        if(pageUserVo.getGender() != null) {
            wrapper.lambda().eq(TbUser::getGender, pageUserVo.getGender());
        }

        // 时间区间查询
        if (StringUtils.isNotEmpty(pageUserVo.getStartDate())) {
            wrapper.lambda().ge(TbUser::getCreateTime, pageUserVo.getStartDate());
        }
        if(StringUtils.isNotEmpty(pageUserVo.getEndDate())) {
            wrapper.lambda().le(TbUser::getCreateTime, pageUserVo.getEndDate());
        }

        Page<TbUser> tbUserPage = tbUserMapper.selectPage(page, wrapper);

        //--3 返回商户列表
        return Result.ok().setData(tbUserPage);
    }

    @Override
    public Result updateUser(TbUser tbUser) {
        //--1 查询商户信息
        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if(user == null) {
            return Result.error().setMsg("商户不存在");
        }

        //--2 修改商户信息
        tbUserMapper.updateById(tbUser);

        return Result.ok();
    }

    @Override
    public Result uploadFile(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);

            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();

            return Result.ok().setData(url);
        } catch (IOException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
            return Result.error().setMsg("上传失败");
        }
    }

    @Override
    public Result deleteUserById(Integer userId) {
        //--1 判断用户是否存在
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null) {
            return Result.error().setMsg("用户不存在");
        }

        //--2 删除用户
        tbUserMapper.deleteById(userId);

        return Result.ok();
    }

    @Override
    public Result deleteUserAll(List<TbUser> userList) {
        //--1 校验参数
        if(userList == null || userList.size() == 0) {
            return Result.error().setMsg("请选择要删除的商户");
        }

        //--2 循环删除商户
        for (TbUser tbUser : userList) {
            tbUserMapper.deleteById(tbUser.getUserId());
        }

        return Result.ok();
    }

    @Override
    public Result checkUser(TbUser tbUser) {
        // 审核不通过，必须填写原因
        if(tbUser.getUserStatus() == 2) {
            if(StringUtils.isEmpty(tbUser.getReason())) {
                return Result.error().setMsg("请输入审核不通过原因");
            }
        }

        // 判断用户是否存在
        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if(user == null) {
            return Result.error().setMsg("用户不存在");
        }

        // 进行审核
        user.setUserStatus(tbUser.getUserStatus());
        user.setReason(tbUser.getReason());
        tbUserMapper.updateById(user);

        return Result.ok();
    }
}




